﻿
@{
    ViewBag.Title = "CivilPriceSingleView";
    Layout = "~/Views/Shared/_MyLayout.cshtml";
}

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>土建核价单操作</legend>
</fieldset>
<form class="layui-form" id="FormInfo">
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline" style="width:300px;">
            <input type="text" id="Name" name="Name" value="" required lay-verify="required" placeholder="请输入核价单名称" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="width:50px;">税率</label>
        <div class="layui-input-inline" style="width:80px;">
            <input type="number" id="TaxRate" name="TaxRate"  placeholder="默认3.3%" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="width:30px;">单位</label>
        <div class="layui-input-inline" style="width:80px;">
            <input type="text" id="Unit" name="Unit" required lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="width:30px;">备注</label>
        <div class="layui-input-inline" style="width:200px;">
            <input type="text" id="Memo" name="Memo"  placeholder="" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-input-inline" style="width:100px;">
            <button type="submit" id="PriceForm" class="layui-btn" lay-submit lay-filter="PriceFormVerify" style="display:none;">立即提交</button>
            <button type="button" class="layui-btn" style="float:left;" id="BtnSave"><i class="layui-icon">&#xe621;</i>保存</button>
        </div>
    </div>
</form>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend style="font-size:16px;">单条表格数据操作</legend>
</fieldset>
<form class="layui-form" id="FormSingle">
    <div class="layui-form-item">
        <label class="layui-form-label">项目名称</label>
        <div class="layui-input-inline" style="width:300px;">
            <input type="text" id="ItemName" required lay-verify="required" placeholder="请输入项目名称" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="width:100px;">工程量计量式</label>
        <div class="layui-input-inline" style="width:500px;">
            <input type="text" id="ItemFormula" placeholder="请输入算式，默认为0" autocomplete="off" class="layui-input">
        </div>
    
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">单位</label>
        <div class="layui-input-inline" style="width:60px;">
            <input type="text" style="width:50px;" id="ItemUnit" required lay-verify="required" placeholder="单位" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="margin-left:-20px;">人工费(单价)</label>
        <div class="layui-input-inline" style="width:100px;">
            <input type="number" id="ItemWorkerPrice" style="width:80px;" max="9999999" placeholder="默认0" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="margin-left:-20px;">材料费(单价)</label>
        <div class="layui-input-inline" style="width:100px;">
            <input type="number" id="ItemMaterialPrice" style="width:80px;"  placeholder="默认0" autocomplete="off" class="layui-input">
        </div>
        <label class="layui-form-label" style="width:35px;margin-left:-20px;">备注</label>
        <div class="layui-input-inline">
            <input type="text" id="ItemMemo" placeholder="输入备注" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-input-inline" style="width:70px;">
            <input type="checkbox" id="SaveType" lay-skin="switch" lay-text="新增|编辑" lay-filter="switch" checked disabled>
        </div>
        <div class="layui-input-inline" style="width:100px;">
            <button type="submit" id="PriceSingleForm" class="layui-btn" lay-submit lay-filter="PriceSingleFormVerify" style="display:none;">立即提交</button>
            <button type="button" class="layui-btn" style="float:left;" id="BtnAddSingle"><i class="layui-icon">&#xe621;</i>保存</button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="margin-left:-20px;width:200px;font-size:16px;">
            <span>人工费合价:</span><span style="color:burlywood" id="WorkerPriceSum"></span>
        </label>
        <label class="layui-form-label" style="margin-left:-20px;width:200px;font-size:16px;">
            <span>材料费合价:</span><span style="color:darkmagenta" id="ItemMaterialPriceSum"></span>
        </label>
        <label class="layui-form-label" style="margin-left:-20px;width:200px;font-size:16px;">
            <span>总价:</span><span style="color:crimson" id="ItemSum"></span>
        </label>
    </div>
</form>
<table class="layui-table" id="demo" lay-filter="TableList"></table>

<script type="text/template" id="PreLayerForm">
@*一下代码为进入该页面时，弹出框设置*@
    <form class="layui-form" id="PreAdd">
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-inline" style="width:300px;">
                <input type="text" id="PreLayerName" name="Name" value="" required lay-verify="required" placeholder="(必填)请输入核价单名称" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label">税率(%)</label>
            <div class="layui-input-inline" style="width:80px;">
                <input type="number" id="PreLayerTaxRate" name="TaxRate"  placeholder="默认3.3%" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单位</label>
            <div class="layui-input-inline" style="width:80px;">
                <input type="text" id="PreLayerUnit" name="Unit" required lay-verify="required" placeholder="必填" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline" style="width:300px;">
                <input type="text" id="PreLayerMemo" name="Memo" value=""  placeholder="请输入备注" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline" style="width:100px;">
                <button type="submit" id="PreLayerSubmit" class="layui-btn" lay-submit lay-filter="PreLayerFormVerify" style="display:none;">立即提交</button>
                <button type="button" class="layui-btn" style="float:left;" id="PreLayerBtnSave"><i class="layui-icon">&#xe621;</i>新增</button>
            </div>
        </div>
    </form>
</script>

<script type="text/javascript">
    var ProjectId = "";
    var state = "";
    var temptr;

    var ItemName = "";//子项目名称
    var ItemUnit = "";//单位
    var ItemWorkerPrice = 0;//人工单价
    var ItemMaterialPrice = 0;//材料单价
    var ItemMemo = "";  //备注 
    var ItemFormula = 0;    //工程计算式结果
    var FormulaValidate = false;
    var WorkerPriceSum = 0;
    var ItemMaterialPriceSum = 0;
    var ItemSum = 0;
    var TaxRate = 0.033;

    //计算值
    function Calculate() {
        //if (FormulaValidate == false) return false;
        WorkerPriceSum = ItemFormula * ItemWorkerPrice;
        ItemMaterialPriceSum = ItemFormula * ItemMaterialPrice;
        ItemSum = ItemFormula * (ItemWorkerPrice + ItemMaterialPrice);

        $("#WorkerPriceSum").text(WorkerPriceSum.toFixed(2));
        $("#ItemMaterialPriceSum").text(ItemMaterialPriceSum.toFixed(2));
        $("#ItemSum").text(ItemSum.toFixed(2));
        FormulaValidate = true;
    }

    //监听各个输入框变化
    $("#ItemFormula").on("input propertychange", function () {
        try {
            if ("" == $("#ItemFormula").val()) {
                ItemFormula = 0;
            }
            else {
                ItemFormula = eval($("#ItemFormula").val());
            } 
            Calculate();
        }
        catch (exception) {
            $("#ItemSum").text("工程量公式有误");
            FormulaValidate = false;
        }
    });

    $("#ItemWorkerPrice").on("input propertychange", function () {
        try {
            if ("" == $("#ItemWorkerPrice").val()) {
                ItemWorkerPrice = 0;
            }
            else {
                ItemWorkerPrice = eval($("#ItemWorkerPrice").val());
            }
            Calculate();
        }
        catch (exception) {
            $("#WorkerPriceSum").text("人工单价有误");
            FormulaValidate = false;
        }
    });

    $("#ItemMaterialPrice").on("input propertychange", function () {
        try {
            if ("" == $("#ItemMaterialPrice").val()) {
                ItemMaterialPrice = 0;
            }
            else {
                ItemMaterialPrice = eval($("#ItemMaterialPrice").val());
            }
            Calculate();
        }
        catch (exception) {
            $("#ItemMaterialPriceSum").text("材料单价有误");
            FormulaValidate = false;
        }
    });
    layui.use([ 'form', 'laydate','table','layer'], function(){
        var form = layui.form;
        var laydate = layui.laydate;
        var table = layui.table;
        var layer = layui.layer;
        var IsValidate = 0;
        var CivilPriceId = "";
        var rowid = "";
        var TempEditData;

        var LayerIndex =layer.open({
            type: 1,
            title:'新建土建核价单',
            area: ['700px', '250px'],
            content: $("#PreLayerForm").html(),
            cancel: function (index, layero) {
                if (confirm('确定要关闭么')) { //只有当点击confirm框的确定时，该层才会关闭
                    layer.close(index);
                    parent.layui.admin.events.closeThisTabs();
                }
                return false;
            }    

        });

        form.on('switch(switch)', function (data) {

            if (this.checked = true) {
                $("#SaveType").prop("disabled", true);
                form.render();
                $(temptr).css("background-color", "white");

            }

        });

        $("#SaveType").on('click', function () {
            var flag = $(this).is(':checked');
            if (flag) {
                $("#SaveType").prop("disabled", true);
                
            }
        });
        //table.render({ elem: '#demo'});
        table.render({
            elem: '#demo'
            , method: 'post'
            //, height: 315
            , url: '/PreEstimate/CivilSingleTableRequest' //数据接口
            , page: true //开启分页
            , where: { SortName: "XMMC", Order: "Desc", Condition: " and 1=0" }
            , limit: 100
            , limits: [100, 500, 1000]
            , cols: [[ //表头
                { field: 'XMMC', title: '项目名称', width: 220, rowspan: 2, align:'center',edit:'text' }
                , { field: 'GCLJSS', title: '工程计量算式', width: 200, rowspan: 2, align: 'center', edit: 'text' }
                , { field: 'DW', title: '单位', width: 80, rowspan: 2, align: 'center', edit: 'text' }
                , {
                    field: 'GCL', title: '工程量', width: 80, rowspan: 2, align: 'center',
                    templet: function (d) {
                        return (d.GCL).toFixed(2);
                    }
                }
                , { title: '人工费', width: 200, colspan: 2, align: 'center' }
                , { title: '材料费', width: 200, colspan: 2, align: 'center' }
                , {
                    title: '总价', rowspan: 2, width: 120, align: 'center',
                    templet: function (d) {
                        return (d.GCL * (d.RGDJ + d.CLDJ)).toFixed(2);
                    }
                }
                , { field: 'Memo', title: '备注', width: 200, rowspan: 2, align: 'center', edit: 'text' }
                , {
                    field: "operation", title: "操作", width: 120, rowspan: 2,
                    templet: function (d) {
                        return '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="Edit">编辑</a><a class="layui-btn layui-btn-xs" lay-event="TableDel">删除</a>';
                    }
                }
                ], [
                    { field: 'RGDJ', title: '单价', width: 80, align: 'center', edit: 'text' }
                    , {
                        title: '合价', width: 120,  align: 'center',
                        templet: function (d) {
                            return (d.GCL * d.RGDJ).toFixed(2);
                        }
                    }
                    , { field: 'CLDJ', title: '单价', width: 80, align: 'center', edit: 'text' }
                    , {
                        title: '合价', width: 120, align: 'center',
                        templet: function (d) {
                            return (d.GCL * d.CLDJ).toFixed(2);
                        }
                    }
                ]]
            , done: function (res, curr, count) {
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                console.log(res);
                var sum = 0;
                var tax = 0;
                for (var i = 0; i < res.data.length; i++) {
                    sum += res.data[i].GCL * (res.data[i].CLDJ + res.data[i].RGDJ);
                }
                if ("" == $("#TaxRate").val()) {
                    TaxRate = 0.033;
                } else {
                    TaxRate = $("#TaxRate").val();
                }
                tax = sum * TaxRate;
                var temphtml = '';
                temphtml = '<tr>' +
                    '<td align="center">税金</td>' +
                    '<td align="center"></td>' +
                    '<td align="center">元</td>' +
                    '<td align="center">' + sum.toFixed(2) + '</td >' +
                    '<td align="center">' + (TaxRate * 100).toFixed(2)+'%</td>' +
                    '<td align="center"></td>' +
                    '<td align="center"></td>' +
                    '<td align="center"></td>' +
                    '<td align="center">' + tax.toFixed(2) + '</td>' +
                    '<td align="center"></td>' +
                    '<td align="center"></td>' +
                    '</tr>';
                temphtml += '<tr style="background-color:#B0E0E6;">' +
                    '<td align="center" colspan="8">合计</td>' +
                    '<td align="center">' + (tax + sum).toFixed(2) + '</td>' +
                    '<td align="center" colspan="2"></td>' +
                    '</tr>';
                $('tbody').append($(temphtml));
            }
        });

        table.on("tool(TableList)", function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if (layEvent == 'Edit') {
                $(temptr).css("background-color", "white");
                $(tr).css("background-color", "#90EE90");
                temptr = tr;
                $("#SaveType").prop('checked', false);
                $("#SaveType").prop('disabled', false);
                form.render();
                $("#ItemName").val(data.XMMC);
                $("#ItemFormula").val(data.GCLJSS);
                $("#ItemUnit").val(data.DW);
                $("#ItemWorkerPrice").val(data.RGDJ);
                $("#ItemMaterialPrice").val(data.CLDJ);
                $("#ItemMemo").val(data.Memo);
                ItemWorkerPrice = data.RGDJ;//人工单价
                ItemMaterialPrice = data.CLDJ;//材料单价
                ItemFormula = eval(data.GCLJSS);    //工程计算式结果
                Calculate();
                rowid = data.Id;

            }

            if (layEvent == 'TableDel') {
                layer.confirm('确实删除：' + data.XMMC, { icon: 3, title: '提示' }, function (index) {
                    //do something
                    $.ajax({
                        type: "POST",
                        url: "/PreEstimate/CivilPriceSingleDel",
                        async: false,
                        data: { "Id": data.Id, "CivilPriceId": CivilPriceId },
                        success: function (msg) {
                            if (msg.result == "OK") {
                                parent.layer.msg('删除成功', { icon: 6, time: 1000 });
                                table.reload('demo', {
                                    where: { SortName: "Id", Order: "asc", Condition: " and CivilPriceId=" + CivilPriceId }
                                });
                                $("#SaveType").prop('checked', true);
                                $("#SaveType").prop('disabled', true);
                                form.render();
                            } else {
                                alert(msg.result);
                            }
                        }
                    });
                    layer.close(index);
                });
                //layer.msg('暂时无法删除', { icon: 0, time: 1000 });
            }

        });

        table.on('edit(TableList)', function (obj)
        { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.value); //得到修改后的值
            console.log(obj.field); //当前编辑的字段名
            console.log(obj.data); //所在行的所有相关数据  
            //layer.alert('之前数据：' + JSON.stringify(TempEditData) + '。当前改变的数据：' + obj.value, {
            //    title: '当前行数据：'
            //});
            var data = obj.data;
            var field = obj.field;
            var tempValidate = 0;

            var Id = data.Id;
            var XMMC = data.XMMC;
            var GCLJSS = data.GCLJSS;
            var DW = data.DW;
            var GCL = data.GCL;
            var RGDJ = data.RGDJ;
            var CLDJ = data.CLDJ;
            var Memo = data.Memo;
            try {
                if (field == "GCLJSS") {
                    if (GCLJSS == "") {
                        GCLJSS = 0;
                    }
                    else {
                        GCL = eval(GCLJSS);
                    }
                }
                if (field == "GCL") {
                    if (GCL == "") {
                        GCL = 0;
                    } else {
                        GCL = eval(GCLJSS).toFixed(2);
                    }
                }
                if (field == "RGDJ") {
                    if (RGDJ == "") {
                        RGDJ = 0;
                    } else {
                        RGDJ = eval(RGDJ).toFixed(2);
                    }
                }
                if (field == "CLDJ") {
                    if (CLDJ == "") {
                        CLDJ = 0;
                    } else {
                        CLDJ = eval(CLDJ).toFixed(2);
                    }
                }
            } catch (e) {
                layer.msg('数据填写格式有误', { icon: 2, time: 1500 });
                table.reload('demo');
                return;
            }
            //下面更新数据
            $.ajax({
                type: "POST",
                url: "/PreEstimate/CivilPriceSingleUpdate",
                async: false,
                data: { "CivilPriceId": CivilPriceId, "Id": Id, "XMMC": XMMC, "GCLJSS": GCLJSS, "DW": DW, "GCL": GCL, "RGDJ": RGDJ, "CLDJ": CLDJ, "Memo": Memo },
                success: function (msg)
                {
                    if (msg.result == "OK") {
                        parent.layer.msg('修改成功', { icon: 6, time: 1000 });
                        table.reload('demo', {
                            where: { SortName: "Id", Order: "asc", Condition: " and CivilPriceId=" + CivilPriceId }
                        });
                        $("#SaveType").prop('checked', true);
                        $("#SaveType").prop('disabled', true);
                        form.render();
                    } else {
                        table.reload('demo');
                        alert(msg.result);
                    }
                }
            });



        });

        //响应单击行事件
        table.on('row(TableList)', function (obj)
        {
            //这里缓存当前行的数据，为编辑做准备
            TempEditData = obj.data;
        });

        //拦截form提交消息
        //拦截页面初始时layer层的form
        form.on('submit(PreLayerFormVerify)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            IsValidate = 1;
            return false;
        });
        //拦截顶部form表单
        form.on('submit(PriceFormVerify)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            IsValidate = 1;
            return false;
        });
        //拦截表格数据操作表单
        form.on('submit(PriceSingleFormVerify)', function (data) {
            //layer.msg(JSON.stringify(data.field));
            IsValidate = 1;
            return false;
        });
        


        $("#PreLayerBtnSave").on("click", function () {
            $("#PreLayerSubmit").click();
            if (IsValidate != 1) return;
            IsValidate = 0;
            var obj = $("#PreAdd").serializeArray();
            var data = {};
            $.each(obj, function (i, v) {
                data[v.name] = v.value;
            });
            $.ajax({
                type: "POST",
                url: "/PreEstimate/AddCivilPrice",
                async: false,
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(data),
                success: function (msg) {
                    if (msg.result == "OK") {
                        parent.layer.msg('新增成功,请增加详细信息', { icon: 6, time: 1000 });
                        //parent.table.reload("demo");
                        //var index = parent.layer.getFrameIndex(window.name);
                        //parent.layer.close(index);
                        CivilPriceId = msg.CivilPriceId;
                        $("#Name").val(msg.Name);
                        $("#TaxRate").val(msg.TaxRate);
                        TaxRate = msg.TaxRate;
                        $("#Unit").val(msg.Unit);
                        $("#Memo").val(msg.Memo);
                        layer.close(LayerIndex);
                        table.reload('demo',{
                            where: { SortName: "XMMC", Order: "Desc", Condition: " and CivilPriceId=" + CivilPriceId }
                        });
                        //parent.layui.admin.events.closeThisTabs();
                    } else {
                        alert(msg.result);
                    }
                }
            });
        });

        $("#BtnSave").on("click", function () {
            $("#PriceForm").click();
            if (IsValidate == 1) {
                IsValidate = 0;
                var obj = $("#FormInfo").serializeArray();
                var data = {};
                $.each(obj, function (i, v) {
                    data[v.name] = v.value;
                });
                //表示编辑
                data["CivilPriceId"] = CivilPriceId;
                $.ajax({
                    type: "POST",
                    url: "/PreEstimate/CivilPriceUpdate",
                    async: false,
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(data),
                    success: function (msg) {
                        if (msg.result == "OK") {
                            parent.layer.msg('修改成功', { icon: 6, time: 1000 });
                            table.reload('demo', {
                                where: { SortName: "Id", Order: "asc", Condition: " and CivilPriceId=" + CivilPriceId }
                            });
                            //parent.table.reload("demo");
                            //var index = parent.layer.getFrameIndex(window.name);
                            //parent.layer.close(index);

                            //parent.layui.admin.events.closeThisTabs();
                        } else {
                            alert(msg.result);
                        }
                    }
                });

            }
        });

        $("#BtnAddSingle").on("click", function () {
            //首先验证输入框正确性
            $("#PriceSingleForm").click();
            if (IsValidate != 1) return;
            IsValidate = 0;
            try {
                if ("" == $("#ItemFormula").val()) {
                    ItemFormula = 0;
                }
                else {
                    ItemFormula = eval($("#ItemFormula").val());
                }
                Calculate();
            }
            catch (exception) {
                $("#ItemSum").text("工程量公式有误");
                FormulaValidate = false;
                return;
            }

            //然后再获取各个值
            var XMMC = $("#ItemName").val();
            var GCLJSS = $("#ItemFormula").val();
            var DW = $("#ItemUnit").val();
            var GCL = eval($("#ItemFormula").val());
            var RGDJ = $("#ItemWorkerPrice").val();
            var CLDJ = $("#ItemMaterialPrice").val();
            var Memo = $("#ItemMemo").val();

            if (GCLJSS == "") {
                GCLJSS = "0";
                GCL = "0";
            }
            if (RGDJ == "") RGDJ = "0";
            if (CLDJ == "") CLDJ = "0";


            //新增的情况
            if (true == $("#SaveType").prop('checked')) {
                $.ajax({
                    type: "POST",
                    url: "/PreEstimate/CivilPriceSingleAdd",
                    async: false,
                    data: { "CivilPriceId": CivilPriceId, "XMMC": XMMC, "GCLJSS": GCLJSS, "DW": DW, "GCL": GCL, "RGDJ": RGDJ, "CLDJ": CLDJ, "Memo": Memo},
                    success: function (msg) {
                        if (msg.result == "OK") {
                            parent.layer.msg('添加成功', { icon: 6, time: 1000 });
                            table.reload('demo', {
                                where: { SortName: "Id", Order: "asc", Condition: " and CivilPriceId=" + CivilPriceId }
                            });
                        } else {
                            alert(msg.result);
                        }
                    }
                });
            }
            if (false == $("#SaveType").prop('checked')) {
                $.ajax({
                    type: "POST",
                    url: "/PreEstimate/CivilPriceSingleUpdate",
                    async: false,
                    data: { "CivilPriceId": CivilPriceId,"Id": rowid, "XMMC": XMMC, "GCLJSS": GCLJSS, "DW": DW, "GCL": GCL, "RGDJ": RGDJ, "CLDJ": CLDJ, "Memo": Memo },
                    success: function (msg) {
                        if (msg.result == "OK") {
                            parent.layer.msg('修改成功', { icon: 6, time: 1000 });
                            table.reload('demo', {
                                where: { SortName: "Id", Order: "asc", Condition: " and CivilPriceId=" + CivilPriceId }
                            });
                            $("#SaveType").prop('checked', true);
                            $("#SaveType").prop('disabled', true);
                            form.render();
                        } else {
                            alert(msg.result);
                        }
                    }
                });
            }

        });


    });
</script>